﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using ShkSimulation.carsharing;
using ShkSimulation.core.dao.input.loader;
using ShkSimulation.core.dao.input.resource;
using ShkSimulation.core.exceptions;
using ShkSimulation.core.template;
using ShkSimulation.core.template.model;
using ShkSimulation.desktop.component.tools;
using ShkSimulation.desktop.setting.model;
using ShkSimulation.desktop.setting.tools;
using FileUtil = ShkSimulation.desktop.util.FileUtil;

namespace ShkSimulation.desktop.setting {
    public partial class NetworkEditForm : Form {
        
        public NetworkEditForm() {
            InitializeComponent();
            DataEditView.MultiSelect = true;
            DataEditView.DragEnter += (sender, args) => {
                if (args.Data.GetDataPresent(typeof(string)) || args.Data.GetDataPresent(DataFormats.Text)) {
                    args.Effect = DragDropEffects.Copy;
                } else {
                    args.Effect = DragDropEffects.None;
                }
            };
            DataEditView.DragDrop += (sender, args) => {
                if (args.Data.GetDataPresent(typeof(string)) || args.Data.GetDataPresent(DataFormats.Text)) {
                    string message = args.Data.GetData(DataFormats.Text).ToString();
                    Point ClientPt = DataEditView.PointToClient(new Point(args.X, args.Y));
                    DataGridView.HitTestInfo hitTest = DataEditView.HitTest(ClientPt.X, ClientPt.Y);
                    DataEditView.CurrentCell = DataEditView.Rows[hitTest.RowIndex].Cells[hitTest.ColumnIndex];
                    DataEditView.BeginEdit(false);
                    DataEditView.CurrentCell.Value = message;
                    DataEditView.EndEdit();
                }
            };
        }
        
        public NetworkEnvironment NetworkInput { get; set; }
        
        private DataTable Demands { get; set; }

        private DataTable Roads { get; set; }

        private DataTable Stations { get; set; }
        
        public Resource DemandResource { get; set; }

        public Resource RoadResource { get; set; }

        public Resource StationResource { get; set; }
        		
        private void NetworkEditForm_Shown(object sender, EventArgs e) {
            InputConfig config = ConfigManager.UserSimulationConfig.Convert();
            if (!CarsharingConfig.IsValidCarsharingConfig(config)) {
                Console.WriteLine($@"配置文件不能正常使用，请重新设置，ShkSimulationDesktop/data中有示例文件");
                MessageBox.Show(@"配置文件不能正常使用，请重新设置", @"提示");
                this.DialogResult = DialogResult.Abort;
                this.Close();
                return;
            }
            ResourceLoader loader = new ExcelResourceLoader();
            NetworkInput = new NetworkEnvironment(config, loader);
            SetEditableItems(NetworkInput);
            this.NetworkEditControl.SetNetworkInputData(Stations, Roads, Demands);
        }

        private void SetEditableItems(NetworkEnvironment networkInput) {
            StationResource = networkInput.AllResources.GetValueOrDefault(CarsharingConfig.StationResourceKey);
            RoadResource = networkInput.AllResources.GetValueOrDefault(CarsharingConfig.RoadResourceKey);
            DemandResource = networkInput.AllResources.GetValueOrDefault(CarsharingConfig.DemandResourceKey);
            if (StationResource == null || StationResource.GetDataTable() == null ||
                RoadResource == null || RoadResource.GetDataTable() == null ||
                DemandResource == null || DemandResource.GetDataTable() == null) {
                throw new ErrorParamException("车站、道路、需求数据不能为空啦啦啦");
            }

            Stations = StationResource.GetDataTable();
            Roads = RoadResource.GetDataTable();
            Demands = DemandResource.GetDataTable();
            
        }

        private void OnItemChanged() {
            this.NetworkEditControl.SetNetworkInputData(Stations, Roads, Demands);
        }

        private void NetworkEditControl_OnStationClick(int index, StationConfigModel obj) {
            SelectedRoadLabel.Text = $@"站台：{obj.Id}";
            DataEditView.DataSource = Stations;
            DataEditView.ClearSelection();
            if (index < DataEditView.Rows.Count) {
                DataEditView.Rows[index].Selected = true;
                DataEditView.FirstDisplayedScrollingRowIndex = index;
            }
        }

        private void NetworkEditControl_OnRoadClick(int index, RoadConfigModel obj) {
            SelectedRoadLabel.Text = $@"道路：{obj.Id}";
            DataEditView.DataSource = Roads;
            DataEditView.ClearSelection();
            if (index < DataEditView.Rows.Count) {
                DataEditView.Rows[index].Selected = true;
                DataEditView.FirstDisplayedScrollingRowIndex = index;
            }
        }

        private void NetworkEditControl_OnDemandClick(int index, DemandConfigModel obj) {
            SelectedRoadLabel.Text = $@"需求：{obj.OriginId}-{obj.DestinationId}";
            DataEditView.DataSource = Demands;
            DataEditView.ClearSelection();
            if (index < DataEditView.Rows.Count) {
                DataEditView.Rows[index].Selected = true;
                DataEditView.FirstDisplayedScrollingRowIndex = index;
            }
        }

        private void AddStationButton_Click(object sender, EventArgs e) {
            int id = Guid.NewGuid().GetHashCode();
            StationConfigModel station = new StationConfigModel(id);
            DataRow row = ConverUtil.EntityToDataRows(Stations, station);
            Stations.Rows.Add(row);
            OnItemChanged();
            NetworkEditControl_OnStationClick(Stations.Rows.Count - 1, station);
        }
        
        private void AddRoadButton_Click(object sender, EventArgs e) {
            int id = Guid.NewGuid().GetHashCode();
            RoadConfigModel roadConfigModel = new RoadConfigModel(id, 1, 2);
            DataRow row = ConverUtil.EntityToDataRows(Roads, roadConfigModel);
            Roads.Rows.Add(row);
            OnItemChanged();
            NetworkEditControl_OnRoadClick(Roads.Rows.Count - 1, roadConfigModel);
        }

        private void AddDemandButton_Click(object sender, EventArgs e) {
            int id = Guid.NewGuid().GetHashCode();
            DemandConfigModel demandConfigModel = new DemandConfigModel(id, 1, 2);
            DataRow row = ConverUtil.EntityToDataRows(Demands, demandConfigModel);
            Demands.Rows.Add(row);
            OnItemChanged();
            NetworkEditControl_OnDemandClick(Demands.Rows.Count - 1, demandConfigModel);
        }

        private void CertainButton_Click(object sender, EventArgs e) {
            string message;
            if (!ModelValidateCheck.CheckValidate(Stations, Roads, Demands, out message)) {
                MessageBox.Show(message, @"提示");
                return;
            }
            if (!ConfigManager.UserSystemConfig.编辑后保存不再提醒) {
                MessageBoxDialogResult messageResult = MessageBoxForm.GetMessageResult(@"提示", @"确认完成编辑吗？会更新文件");
                ConfigManager.UserSystemConfig.编辑后保存不再提醒 = MessageBoxForm.Ignore(messageResult);
                if ((messageResult & MessageBoxDialogResult.Cancel) != 0) {
                    return;
                }
            }
            this.DialogResult = DialogResult.Yes;
            ResourceLoader loader = new ExcelResourceLoader();
            Console.WriteLine($@"更新输入文件");
            loader.SaveData(StationResource);
            loader.SaveData(RoadResource);
            loader.SaveData(DemandResource);
            this.Close();
        }

        private void DeleteItemButton_Click(object sender, EventArgs e) {
            if (DataEditView.DataSource == null) {
                return;
            }
            if (DataEditView.SelectedRows.Count > 0) {
                List<int> selectedRowIds = new List<int>();
                foreach (DataGridViewRow selectedRow in DataEditView.SelectedRows) {
                    selectedRowIds.Add(selectedRow.Index);
                }
                selectedRowIds.Sort();
                selectedRowIds.Reverse();
                foreach (var selectedRowId in selectedRowIds) {
                    ((DataTable)DataEditView.DataSource).Rows.RemoveAt(selectedRowId);
                }
                this.NetworkEditControl.SetNetworkInputData(Stations, Roads, Demands);
            }
        }

        private void CancelButton_Click(object sender, EventArgs e) {
            if (!ConfigManager.UserSystemConfig.编辑后取消不再提醒) {
                MessageBoxDialogResult messageResult = MessageBoxForm.GetMessageResult(@"提示", @"内容会丢失哦？");
                ConfigManager.UserSystemConfig.编辑后取消不再提醒 = MessageBoxForm.Ignore(messageResult);
                if ((messageResult & MessageBoxDialogResult.Cancel) != 0) {
                    return;
                }
            }
            this.Close();
        }

        private void ExportResourceButton_Click(object sender, EventArgs e) {
            if (DataEditView.DataSource == null) {
                MessageBox.Show(@"请选择要导出的数据", @"提示");
                return;
            }
            string saveFilePath;
            ResourceLoader loader = new ExcelResourceLoader();
            if (DataEditView.DataSource == Stations) {
                saveFilePath = FileUtil.SaveFile(SaveFileDialog, $@"保存站台文件", $@"站台数据|*.xlsx", $"station.xlsx");
                if (saveFilePath == null) {
                    return;
                }
                loader.SaveData(StationResource, saveFilePath);
            }else if (DataEditView.DataSource == Roads) {
                saveFilePath = FileUtil.SaveFile(SaveFileDialog, $@"保存道路文件", $@"道路数据|*.xlsx", $"road.xlsx");
                if (saveFilePath == null) {
                    return;
                }
                loader.SaveData(RoadResource, saveFilePath);
            }else if (DataEditView.DataSource == Demands) {
                saveFilePath = FileUtil.SaveFile(SaveFileDialog, $@"保存需求文件", $@"需求数据|*.xlsx", $"demand.xlsx");
                if (saveFilePath == null) {
                    return;
                }
                loader.SaveData(DemandResource, saveFilePath);
            }
        }

    }

}
